//
//  NSDictionaryAdditions.m
//  Tint
//
//  Created by Kevin Wu on 2/22/12.
//  Copyright (c) 2012 Telligenty. All rights reserved.
//

#import "NSDictionaryAdditions.h"
#import "NSStringAdditions.h"


@implementation NSDictionary (Tint)


#pragma mark - Querying

- (BOOL)hasObjectEqualTo:(id)object
{
    return ( [[self allValues] indexOfObject:object] != NSNotFound );
}

- (BOOL)hasObjectIdenticalTo:(id)object
{
    return ( [[self allValues] indexOfObjectIdenticalTo:object] != NSNotFound );
}

- (BOOL)hasKeyEqualTo:(id)key
{
    return ( [[self allKeys] indexOfObject:key] != NSNotFound );
}

- (BOOL)hasKeyIdenticalTo:(id)key
{
    return ( [[self allKeys] indexOfObjectIdenticalTo:key] != NSNotFound );
}



#pragma mark - URL

- (NSString *)newQueryString
{
    if ( [self count] > 0 ) {
        
        NSMutableArray *parameters = [[NSMutableArray alloc] init];
        
        for ( NSString *key in [self keyEnumerator] ) {
            NSString *value = [self objectForKey:key];
            NSString *encodedValue = [value newURLEncodedString];
            NSString *pair = [[NSString alloc] initWithFormat:@"%@=%@", key, encodedValue];
            [parameters addObject:pair];
            [pair release];
            [encodedValue release];
        }
        
        NSMutableString *queryString = nil;
        
        if ( [parameters count] > 0 ) {
            
            queryString = [[NSMutableString alloc] init];
            [queryString appendString:[parameters objectAtIndex:0]];
            
            for ( int i=1; i<[self count]; ++i ) {
                NSString *parameter = [parameters objectAtIndex:i];
                [queryString appendString:@"&"];
                [queryString appendString:parameter];
            }
            
        }
        
        [parameters release];
        
        return queryString;
    }
    return nil;
}

@end




@implementation NSMutableDictionary (Tint)


#pragma mark - Adding and removing entries

- (void)setObject:(id)object forKeyIfNotNil:(id)key
{
    if ( object && key ) {
        [self setObject:object forKey:key];
    }
}

- (void)removeObjectForKeyIfNotNil:(id)key
{
    if ( key ) {
        [self removeObjectForKey:key];
    }
}

@end

